package cn.lili.modules.order.order.callback;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.vo.ResponseBean;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.goods.client.GoodsClient;
import cn.lili.modules.goods.entity.vos.yunxin.CallBackVO;
import cn.lili.modules.goods.entity.vos.yunxin.LogisticsInfoVO;
import cn.lili.modules.goods.entity.vos.yunxin.ProductVO;
import cn.lili.modules.order.order.client.OrderClient;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.order.order.entity.dos.OrderItem;
import cn.lili.modules.order.order.entity.dto.OrderMessage;
import cn.lili.modules.order.order.entity.enums.DeliverStatusEnum;
import cn.lili.modules.order.order.entity.enums.OrderComplaintStatusEnum;
import cn.lili.modules.order.order.entity.enums.OrderItemAfterSaleStatusEnum;
import cn.lili.modules.order.order.entity.enums.OrderStatusEnum;
import cn.lili.modules.order.order.service.MessageTypeFlowService;
import cn.lili.modules.order.order.service.OrderItemService;
import cn.lili.modules.order.order.service.OrderService;
import cn.lili.modules.system.client.LogisticsClient;
import cn.lili.modules.system.entity.dos.Logistics;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单发货
 */
@Slf4j
@Service("order.delivery")
public class OrderDeliveryService implements MessageType {

    @Autowired
    private MessageTypeFlowService messageTypeFlowService;

    @Autowired
    private LogisticsClient logisticsClient;

    @Autowired
    @Lazy
    private OrderService orderService;

    @Autowired
    @Lazy
    private OrderItemService orderItemService;

    @Autowired
    private GoodsClient goodsClient;

    @Override
    public ResponseBean execute(CallBackVO callBackVO) {
        log.info("goods.undercarriage == {}", JSONObject.toJSONString(callBackVO));
        //写入物流信息
        OrderItem orderItem = orderItemService.getBySn(callBackVO.getOrder_sn());
        Order order = orderService.getBySn(orderItem.getOrderSn());
        if (order == null) {
            log.error("callBackVO.getOrder_sn() === {}", callBackVO.getOrder_sn());
            throw new ServiceException("根据order_sn,未获取到订单信息");
        }
        //保存回调消息记录
        messageTypeFlowService.saveCall(callBackVO);

        //获取供应链的物流信息
        JSONArray jsonArray = this.getOrder(callBackVO.getOrder_sn());
        if (jsonArray == null) {
            log.error("获取供应链的物流信息为空 == {}",  callBackVO.getOrder_sn());
            throw new ServiceException("获取供应链的物流信息为空");
        }
        for (Object o : jsonArray) {
            LogisticsInfoVO logisticsInfoVO = JSONObject.parseObject(String.valueOf(o), LogisticsInfoVO.class);
            Logistics logistics = logisticsClient.getByName(logisticsInfoVO.getCompany_name());
            if (logistics == null) {
                //可能他们库中有这个物流公司但，我们没有。检查到这个日志时把name + code 放到我们库中。
                log.error("未获取到物流公司===name{}, code === {} ", logisticsInfoVO.getCompany_name(), logisticsInfoVO.getCompany_code());
                order.setLogisticsName(logisticsInfoVO.getCompany_name());
                order.setLogisticsCode(logisticsInfoVO.getCompany_code());
//                throw new ServiceException(ResultCode.ORDER_LOGISTICS_ERROR);
            }
            if (logistics != null) {
                order.setLogisticsCode(logistics.getId());
                order.setLogisticsName(logistics.getName());
            }
            order.setLogisticsNo(logisticsInfoVO.getExpress_no());
            order.setLogisticsTime(new Date());
            order.setDeliverStatus(DeliverStatusEnum.DELIVERED.name());
            order.setOrderStatus(OrderStatusEnum.DELIVERED.name());
            orderService.updateById(order);
        }
        //修改订单货物可以进行售后、投诉
        orderItemService.update(new UpdateWrapper<OrderItem>().eq("order_sn", orderItem.getOrderSn()).set("after_sale_status",
                OrderItemAfterSaleStatusEnum.NOT_APPLIED).set("complain_status", OrderComplaintStatusEnum.NO_APPLY));
        //发送订单状态改变消息
        OrderMessage orderMessage = new OrderMessage();
        orderMessage.setNewStatus(OrderStatusEnum.DELIVERED);
        orderMessage.setOrderSn(order.getSn());
        orderService.sendUpdateStatusMessage(orderMessage);

        return new ResponseBean(0, "操作成功", new HashMap<>());
    }


    /**
     * 获取订单信息
     *
     * @param orderSn 订单号
     * @return
     */
    private JSONArray getOrder(String orderSn) {
        String token = goodsClient.getToken();
        Map<String,Object> params = new HashMap<>();
        params.put("order_sn", orderSn);
        HttpRequest httpRequest = HttpUtil.createPost("https://supply.yibangjiu.com/supplyapi" + "/app/order/Logistic").header("x-token", token).body(JSONObject.toJSONString(params));
        String body = httpRequest.execute().body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (jsonObject.getInteger("code") != 0) {
            throw new ServiceException("获取分类异常");
        }
        JSONArray jsonArray = (JSONArray) jsonObject.get("data");
        return jsonArray;
    }
}
